var path = require('path');
var fs = require('fs');

var pwd = path.resolve(__dirname);
var assetsImageDir = path.resolve(__dirname, '../assets/images')
var libAssetsImageFile = path.resolve(__dirname, '../lib/constants/ImageAssets.dart');

function writeImageAssets() {
  const images = [];
  mapDir(assetsImageDir, (file)=> {
    var relativeFilePath = file.substring(file.indexOf('assets/images'));
    var names = relativeFilePath.split(/[\_\/\.\-]/).splice(2);
    var name = names.map((value, index)=> {
      return index == 0 ? value : value[0].toUpperCase() + value.substring(1);
    }).join("");
    images.push(imageTmpl(name, relativeFilePath));
  }, () => {
    var list = images.sort((a, b)=> a.localeCompare(b))
    var fileContent = imageAssetsTmpl(list.join("\n"))
    fs.writeFileSync(libAssetsImageFile, fileContent, {
      encoding: "utf-8"
    })
  })
}

function mapDir(dir, callback, finish) {
  fs.readdir(dir, function(err, files) {
    if (err) {
      console.error(err)
      return
    }
    files.forEach((filename, index) => {
      let pathname = path.join(dir, filename)
      const stats = fs.statSync(pathname)
      if(!stats) {
        console.log('获取文件stats失败')
        return
      }
      if (stats.isDirectory()) {
        mapDir(pathname, callback, finish)
      } else if (stats.isFile()) {
        if(
          ['.jpg', '.png'].includes(path.extname(pathname)) &&
          (pathname.includes('@2x') || pathname.includes('@3x'))
        ) {
          var list = pathname.split("/");
          var name = list[list.length - 1].split(/@\dx/).join("");
          if(pathname.includes('@2x')) list.splice(list.length - 1,1, `2.0x/${name}`)
          if(pathname.includes('@3x')) list.splice(list.length - 1,1, `3.0x/${name}`)
          var targetFile = list.join("/");
          if(!fs.existsSync(path.dirname(targetFile))) {
            fs.mkdirSync(path.dirname(targetFile));
          }
          fs.renameSync(pathname, targetFile);
          return;
        }
        if(
          ['.jpg', '.png'].includes(path.extname(pathname)) &&
          !(pathname.includes('2.0x') || pathname.includes('3.0x'))
        ) {
          callback && callback(pathname)
        }
      }
      if (index === files.length - 1) {
        finish && finish()
      }
    })
  })
}


var imageAssetsTmpl = (images) => {
  return `
class ImageAssets {
${images}
}
  `;
}

var imageTmpl = (name, path) => {
  return `\t\tstatic String ${name} = "${path}";`;
}


writeImageAssets();

